package com.starwish.starwishblog.web.back;

import com.github.pagehelper.PageInfo;

import com.starwish.starwishblog.entity.User;
import com.starwish.starwishblog.result.ResultResponse;
import com.starwish.starwishblog.service.UserService;

import com.starwish.starwishblog.vo.HistoryVo;
import com.starwish.starwishblog.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("admin/user")
@Slf4j
@Api(value = "用户登录")
public class UserController {
    @Autowired
    UserService userService;
    @Value("${starwish.user}")
    String path;
    //用户注册  添加用户
    @PostMapping("/register")
    public ResultResponse<Void> register(@RequestBody User user){
        ResultResponse<Void> result = null;
        try{
           String nickName = "";
           nickName ="用户名"+ UUID.randomUUID().toString().replaceAll("-", "").substring(24,30);
           user.setNickname(nickName);
           user.setIsDelete("0");
           user.setFanCount(0);
           user.setFollowCount(0);
           user.setCreateTime(new Date());
           user.setModifyTime(new Date());
           user.setLastLogin(new Date());
          int i = userService.registerUserByKey(user);
          if(i>0){
            result = new ResultResponse<>(200,"注册成功");
          }else {
              result = new ResultResponse<>(201,"注册失败");
          }
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(305,"注册异常");
        }
        return result;
    }
    @GetMapping("/followList")
    @ApiOperation(value = "用户关注列表")
    public ResultResponse<PageInfo<UserVo>> followList(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            String name){
        ResultResponse<PageInfo<UserVo>> result = null;
        System.out.println("dasdasdas   "+name);
        try {
            PageInfo<UserVo> pageInfo = userService.queryByPages(now, size, name);
            result = new ResultResponse<>(200,"用户关注列表查询成功",pageInfo);

        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"用户关注列表查询失败");
        }
        return result;
    }

    @GetMapping("/FanListById")
    @ApiOperation(value = "用户关注列表")
    public ResultResponse<PageInfo<UserVo>> FanListById(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            @ApiParam(name = "id",value = "博主Id") @RequestParam("id") Integer id){
        ResultResponse<PageInfo<UserVo>> result = null;
        try {
            PageInfo<UserVo> pageInfo = userService.queryFansById(now,size,id);
            result = new ResultResponse<>(200,"加载粉丝列表查询成功",pageInfo);

        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载粉丝列表查询失败");
        }
        return result;
    }
    @GetMapping("/FanList")
    @ApiOperation(value = "用户关注列表")
    public ResultResponse<PageInfo<UserVo>> FanList(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            String username){
        ResultResponse<PageInfo<UserVo>> result = null;
        try {
            PageInfo<UserVo> pageInfo = userService.queryFans(now,size,username);
            result = new ResultResponse<>(200,"加载粉丝列表查询成功",pageInfo);

        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载粉丝列表查询失败");
        }
        return result;
    }

    @PostMapping("/addFollow")
    public ResultResponse<Void> addFollow(@ApiParam(name = "userId",value = "用户的ID") @RequestParam(value = "userId") Integer userId,
                                          @ApiParam(name = "authorId",value = "被关注用户的ID") @RequestParam(value = "authorId") Integer authorId){
        ResultResponse<Void> result = null;
        try{
            userService.addFollowUser(userId,authorId);
            result = new ResultResponse<>(200,"添加关注成功");
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(200,"添加关注失败");
        }
        return result;
    }

    @PutMapping("/cancelFollowUser")
    public ResultResponse<Void> cancelFollowUser(@ApiParam(name = "userId",value = "用户的ID") @RequestParam(value = "userId") Integer userId,
                                                 @ApiParam(name = "authorId",value = "被关注用户的ID") @RequestParam(value = "authorId") Integer authorId){
        ResultResponse<Void> result = null;
        try{
            int i = userService.cancelFollowUserByKey(userId, authorId);
            if(i>0){
            result = new ResultResponse<>(200,"取消关注成功");
            }else {
                result = new ResultResponse<>(201,"取消关注失败");

            }
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(305,"取消关注异常");
        }
        return result;
    }

    @GetMapping("/uList")
    @ApiOperation(value = "后台查看用户表")
    public ResultResponse<PageInfo<UserVo>> uList(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            String username){
        ResultResponse<PageInfo<UserVo>> result = null;
        try {
            PageInfo<UserVo> pageInfo = userService.queryUserAndFanCountByPages(now, size, username);
            result = new ResultResponse<>(200,"加载用户和粉丝数列表查询成功",pageInfo);

        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载用户和粉丝数列表查询失败");
        }
        return result;
    }
    //用户修改
    @PutMapping("/modify")
    @ApiOperation(value = "用户修改")
    public ResultResponse<Void> modify(@RequestBody User user) {
        ResultResponse<Void> result = null;
        try {
            user.setModifyTime(new Date());
            int i = userService.modifyUserByKey(user);
            if (i > 0) {
                result = new ResultResponse<>(200, "更新成功");
            } else {
                result = new ResultResponse<>(201, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultResponse<>(200, "更新权限异常");
        }
        return result;
    }
    //用户删除
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "删除用户")
    public ResultResponse<Void> del(@ApiParam(name = "id",value = "用户的ID") @PathVariable("id") Integer id){
        ResultResponse<Void> result = null;
        try{
            int i = userService.deleteUserByKey(id);
            if(i == 1){
                result = new ResultResponse<>(200, "删除用户成功！");
            }else {
                result = new ResultResponse<>(201, "删除用户失败！");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            result = new ResultResponse<>(305, "删除用户异常");
        }
        return result;
    }
    //更具Id查询用户
    @GetMapping("/findUserByKey/{id}")
    public ResultResponse<User> findUserByKey(@ApiParam(name = "id",value = "查询用户用的Id") @PathVariable("id") Integer id){
        ResultResponse<User> result = null;
        try{
            User user = userService.queryUserByKey(id);
            if(user ==null){
                result = new ResultResponse<>(201, "查询用户失败！");
            }else {
                result = new ResultResponse<>(200, "查询用户成功！",user);
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(305, "查询用户异常！");

        }
            return result;
    }

    @GetMapping("/changeLocked")
    public ResultResponse<Void> changeLocked(@RequestParam("id")Integer id,@RequestParam("status") Integer status){
        ResultResponse<Void> result = null;
        try {
            int i = userService.updateLocked(id,status);
            if(i > 0){
                result = new ResultResponse<>(200,"修改成功");
            }else{
                result = new ResultResponse<>(201,"修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultResponse<>(305,"系统错误");
        }
        return result;
    }

    @GetMapping("/hList")
    @ApiOperation(value = "后台查看用户表")
    public ResultResponse<PageInfo<HistoryVo>> hList(
            @RequestParam(value = "now",defaultValue = "1") Integer now,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            String username){
        ResultResponse<PageInfo<HistoryVo>> result = null;
        try {
            PageInfo<HistoryVo> pageInfo = userService.queryUserHistoryByPages(now, size, username);
            result = new ResultResponse<>(200,"加载浏览历史列表查询成功",pageInfo);

        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"加载浏览历史数列表查询失败");
        }
        return result;
    }

    @PostMapping("/addHistory")
    @ApiOperation("添加历史记录")
    public ResultResponse<Void> addHistory(@ApiParam(name = "userId",value = "用户的ID") @RequestParam(value = "userId") Integer userId,
                                          @ApiParam(name = "articleId",value = "文章ID") @RequestParam(value = "articleId") Integer articleId){
        ResultResponse<Void> result = null;
        try{
            HistoryVo historyVo = new HistoryVo();
            historyVo.setUserId(userId);
            historyVo.setArticleId(articleId);
            historyVo.setCreateTime(new Date());
           int i = userService.insertHistoryById(historyVo);
            result = new ResultResponse<>(200,"添加历史记录成功");
        }catch (Exception e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"添加历史记录失败");
        }
        return result;
    }

    @DeleteMapping("/delHistory/{id}")
    @ApiOperation(value = "删除单条的历史记录")
    public ResultResponse<Void> delHistory(@ApiParam(name = "id",value = "历史记录的ID") @PathVariable("id") Integer id){
        ResultResponse<Void> result = null;
        try{
            int i = userService.deleteUserHistoryByKey(id);
            if(i == 1){
                result = new ResultResponse<>(200, "删除历史记录成功！");
            }else {
                result = new ResultResponse<>(201, "删除历史记录失败！");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            result = new ResultResponse<>(305, "删除历史记录异常");
        }
        return result;
    }
    @DeleteMapping("/delHistoryByUserId/{id}")
    @ApiOperation(value = "删除单条的历史记录")
    public ResultResponse<Void> delHistoryByUserId(@ApiParam(name = "id",value = "用户的ID") @PathVariable("id") Integer id){
        ResultResponse<Void> result = null;
        try{
            int i = userService.deleteUserHistoryByUserId(id);
            if(i>0){
                result = new ResultResponse<>(200, "删除用户的历史记录成功！");
            }else {
                result = new ResultResponse<>(201, "删除用户的历史记录失败！");
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            result = new ResultResponse<>(201, "删除用户的历史记录异常");
        }
        return result;
    }

    @PutMapping("/recoverUserHistory")
    @ApiOperation(value = "恢复用户浏览历史记录")
    public ResultResponse<Void> recoverUserHistory(@ApiParam(name = "userId",value = "用户Id") @RequestParam("userId") Integer userId) {
        ResultResponse<Void> result = null;
        try {
            int i = userService.recoverUserHistoryByKey(userId);
            if (i > 0) {
                result = new ResultResponse<>(200, "恢复成功");
            } else {
                result = new ResultResponse<>(201, "恢复失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultResponse<>(200, "更新权限异常");
        }
        return result;
    }

    @GetMapping("/recoverAllHistory")
    @ApiOperation(value = "恢复所有浏览历史记录")
    public ResultResponse<Void> recoverAllHistory() {
        ResultResponse<Void> result = null;
        try {
            int i = userService.recoverAllUserHistory();
            if (i > 0) {
                result = new ResultResponse<>(200, "恢复成功");
            } else {
                result = new ResultResponse<>(201, "恢复失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultResponse<>(200, "恢复异常");
        }
        return result;
    }

    @GetMapping("/deleteAllHistory")
    @ApiOperation(value = "删除所有浏览历史记录")
    public ResultResponse<Void> deleteAllHistory() {
        ResultResponse<Void> result = null;
        try {
            int i = userService.deleteAllUserHistory();
            if (i > 0) {
                result = new ResultResponse<>(200, "删除成功");
            } else {
                result = new ResultResponse<>(201, "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultResponse<>(200, "删除异常");
        }
        return result;
    }

    @GetMapping("/changeHistoryIsDelete")
    @ApiOperation("更具id修改isDelete")
    public ResultResponse<Void> changeHistoryIsDelete(@RequestParam("id")Integer id,@RequestParam("isDelete") Integer isDelete){
        ResultResponse<Void> result = null;
        try {
            int i = userService.updateHistory(id,isDelete);
            if(i > 0){
                result = new ResultResponse<>(200,"修改成功");
            }else{
                result = new ResultResponse<>(201,"修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultResponse<>(305,"系统错误");
        }
        return result;
    }
    @PostMapping("/upload")
    public ResultResponse<String> upload(@RequestParam(value = "userImg") MultipartFile multipartFile){
        ResultResponse<String> result = null;
        try {
            String filename = multipartFile.getOriginalFilename();
            log.info("上传的原名字"+filename);
            filename = UUID.randomUUID().toString().replace("-", "")+filename.substring(filename.lastIndexOf("."));
            log.info("上传后的文件名"+filename);
            File file = new File(path);
            if(!file.exists()){
                file.mkdir();
            }
            File f = new File(file,filename);
            multipartFile.transferTo(f);
            result = new ResultResponse<>(200,"上传成功!",filename);
        }catch (IOException e){
            e.printStackTrace();
            result = new ResultResponse<>(202,"上传异常!");
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(202,"上传异常!");
        }
            return result;
    }

}
